package register

import (
	"fmt"
	"go-proxy/common"
	"go-proxy/config"
	"sync"
)

var (
	centerRegisterHandler = make(map[string]CenterRegister)
	registerLock          sync.RWMutex
)

type InstanceInfo struct {
	Address string `json:"address"`
	Port    uint64 `json:"port"`
	Host    string `json:"host"`
}

type CenterRegister interface {
	InitService(service *config.Service) error

	GetInstances(service *config.Service, route *config.Route) ([]*InstanceInfo, error)
}

func InitRegisterCenter(service *config.Service) error {
	if len(service.Type) <= 0 {
		return nil
	}

	registerLock.Lock()
	defer registerLock.Unlock()

	var centerRegister CenterRegister
	if service.Type == common.ConsulService {
		centerRegister = NewConsulService()
	}

	if service.Type == common.NacosService {
		centerRegister = NewNacosService()
	}

	if centerRegister == nil {
		return fmt.Errorf("register type %s not support", service.Type)
	}

	err := centerRegister.InitService(service)
	if err != nil {
		return err
	}
	centerRegisterHandler[service.Name] = centerRegister
	return nil
}

func GetServiceInstances(service *config.Service, route *config.Route) ([]*InstanceInfo, error) {
	registerLock.RLock()
	defer registerLock.RUnlock()

	registerCenter, ok := centerRegisterHandler[route.TargetService]
	if !ok {
		return nil, fmt.Errorf("register %s not found", route.TargetService)
	}
	return registerCenter.GetInstances(service, route)
}
